<?php

namespace G4T\Form\Filter;

class ImageFilter implements \Zend_Filter_Interface
{
    private $width;
    private $height;
    private $dir;

    public function __construct($width, $height, $dir)
    {
        $this->width = $width;
        $this->height = $height;
        $this->dir = $dir;
    }


    /**
     * Returns the result of filtering $value
     *
     * @param  mixed $value
     * @throws Zend_Filter_Exception If filtering $value is impossible
     * @return mixed
     */
    public function filter($value)
    {
        $baseDir = dirname(APPLICATION_PATH) . DIRECTORY_SEPARATOR . 'public'
            . DIRECTORY_SEPARATOR . $this->dir . DIRECTORY_SEPARATOR;
        $image = new \Imagick($value);
        $image->thumbnailimage($this->width, $this->height);
        $image->writeimage($value);
        $char = 0;
        do {
            $newFile = preg_replace('/\/{2,}/', '/', $baseDir . $char . pathinfo($value, PATHINFO_BASENAME));
            $char++;
        } while (file_exists($newFile));
        rename($value, $newFile);
        return $newFile;
    }
}
